from django.db import models
from django.shortcuts import reverse


class Category(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True)
    slug = models.SlugField(unique=True)
    featured = models.BooleanField(default=None)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.title

    def to_dict(self):
        return {'title': self.title, 'description': self.description,
                'slug': self.slug}


class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True)
    category = models.ManyToManyField(Category, null=True, blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=65, default=9.99,
                                verbose_name='即时价格')
    sale_price = models.DecimalField(decimal_places=2, max_digits=65,
                                     null=True, blank=True)
    slug = models.SlugField(unique=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)
    update_defaults = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("product:single_product", kwargs={"slug": self.slug})

    def to_dict(self):
        return {"title": self.title, "price": self.price,
                "sale_price": self.sale_price, "url": self.get_absolute_url(),
                "images": [img.to_dict() for img in
                           self.productimage_set.all()]}


class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products/images/')
    featured = models.BooleanField(default=False)
    thumbnail = models.BooleanField(default=False)
    active = models.BooleanField(default=True)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return self.product.title

    def to_dict(self):
        return {"img_url": self.image.url}
